<template>
  <div>
  <!-- <div @click="toggleAudio"> -->
    <audio :src="src" type="audio/mp3" controls ref="audioRef"></audio>
    <div class="flex-cc" :style="{color: isProfessor ? '#D7AE3C' : '#FFF'}">
      <img v-if="isProfessor" src="../../static/voice3.png" alt="" style="margin-right: 8px;" />
      {{ audioTime }}<span style="width: 5px;margin-left: 3px;"> ”</span>
      <img v-if="!isProfessor" src="../../static/voice2.png" alt="" style="margin-left: 8px;" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'index',
  props: {
    src: {
      type: String,
      default: ''
    },
    audioTime: {
      type: String,
      default: ''
    },
    isProfessor: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      audioElement: null,
      isPlaying: false
    };
  },
  mounted () {
    this.audioElement = uni.createInnerAudioContext();
    this.audioElement.src = this.src;
    this.audioElement.onEnded(() => {
      this.audioElement.seek(0);
      this.audioElement.currentTime = 0;
      this.isPlaying = false;
      this.audioElement.offEnded(); // 移除监听器
    });
  },
  methods: {
    toggleAudio () {
      if (this.isPlaying) {
        console.log('1', 1)
        this.audioElement.pause();
        // this.audioElement.seek(0.01);
        // this.audioElement.currentTime = 0;
        this.resetAudio()
        console.log("🚀 ~ file: index.vue:50 ~ toggleAudio ~ this.audioElement:", this.audioElement, this.audioElement.currentTime)
        this.isPlaying = false;
      } else {
        console.log('2', 2)
        this.audioElement.play();
        this.isPlaying = true;
      }
    },
    resetAudio () {
      this.audioElement.resetAudio(); // 重新加载音频资源
      this.audioElement.play();
      this.audioElement.pause();
    },
  }
}
</script>

<style scoped>
img {
  width: 14px;
}
audio {
  display: none;
  z-index: -1;
}
</style>